<?php
/**
 * Created by lzl
 * Date: 2021 2021/9/8
 * Time: 9:21
 */
namespace App\Forms;

use App\Models\Banner;
use Illuminate\Database\Query\Builder;


class BannerForms extends BaseForm
{

    /**
     * @param $validated
     * @return mixed
     */
    public function getBannerList($validated = [])
    {


        $list = Banner::where(function($q) use ($validated) {
            /**
             * @var Builder $q
             */
            if(isset($validated['type']) && isset($validated['type'])){

                $q->where('type', $validated['type']);
            }

            return $q;

        })->page(function($q) use ($validated){

                if(isset($validated['page']) && isset($validated['limit'])){
                    $q->page($validated['page'], $validated['limit']);
                }

                return $q;
        })->orderBy('sort', 'desc')->get();


        return $list;
    }






    /**
     * @param $validated
     * @return Banner|\Illuminate\Database\Eloquent\Model
     * @throws \App\Exceptions\RequestException
     */
    public function editBanner($validated)
    {
        return Banner::updateOrCreate(['id' => $validated['id'] ?? 0 ], $validated);
    }


    /**
     * @param $validated
     * @return int
     */
    public function delete($validated)
    {
        return Banner::destroy($validated['id']);
    }


    /**
     * @param $validated
     * @return Banner|\Illuminate\Database\Eloquent\Model
     */
    public function getBannerOrNew($validated)
    {
        return Banner::firstOrNew(['id' => $validated['id'] ?? 0]);
    }

}